﻿using Demo.Domains.Entities.Sys;
using Demo.PetaPoco.Application.DbContexts;
using Microsoft.Extensions.DependencyInjection;
using PmSoft.Core;
using PmSoft.Data.PetaPoco.Repositories;

namespace Demo.PetaPoco.Application.Services.Config;

/// <summary>
/// 通用配置仓储类，负责配置的获取和保存操作
/// </summary>
[Inject(ServiceLifetime.Scoped)]
public class ConfigRepository : CacheRepository<AppDbContext, SysConfig, string>
{
	/// <summary>
	/// 构造函数，初始化仓储上下文
	/// </summary>
	/// <param name="dbContext">数据库上下文</param>
	/// <param name="applicationContext">应用上下文</param>
	public ConfigRepository(AppDbContext dbContext, IApplicationContext applicationContext)
		: base(dbContext, applicationContext)
	{
	}

	/// <summary>
	/// 异步获取配置
	/// </summary>
	public async Task<TConfig?> GetAsync<TConfig>(string configKey)
		where TConfig : class, new()
	{
		var sysConfig = await base.GetAsync(configKey);
		return sysConfig?.ConfigValue != null
			? Json.Parse<TConfig>(sysConfig.ConfigValue)
			: null;
	}

    /// <summary>
    /// 异步保存配置
    /// </summary>
    public async Task SaveAsync<TConfig>(string configKey, TConfig config)
        where TConfig : class, new()
    {
        var sysConfig = await base.GetAsync(configKey);
        var configValue = Json.Stringify(config);
        if (sysConfig == null)
        {
            await base.InsertAsync(new SysConfig
            {
                Id = configKey,
                ConfigValue = configValue
            });
        }
        else
        {
            sysConfig.ConfigValue = configValue;
            await base.UpdateAsync(sysConfig);
        }
    }

}